package com.xnfh.network.interceptor

import com.xnfh.network.constant.BASEURL
import com.xnfh.network.constant.BASE_SFJ_URL
import com.xnfh.network.constant.BASE_URL_OTHER
import com.xnfh.network.constant.BASE_URL_OTHER1
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Response


/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/10 09:58
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/10 09:58
 * @UpdateRemark: 更新说明
 */
class BaseUrlInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val oldHttpUrl: HttpUrl? = request.url()
        val newBuilder = request.newBuilder()
        val headers = request.headers(BASEURL)
        if (!headers.isNullOrEmpty()) {
            var newBaseUrl: HttpUrl? = null
            //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
            newBuilder.removeHeader(BASEURL)
            if (headers[0].equals(BASE_URL_OTHER)) {
                //设置其他baseurl
                newBaseUrl = HttpUrl.parse(BASE_URL_OTHER)
            }else if(headers[0].equals(BASE_URL_OTHER1)){
                //设置其他baseurl
                newBaseUrl = HttpUrl.parse(BASE_URL_OTHER1)
            }else if(headers[0].equals(BASE_SFJ_URL)){
                newBaseUrl = HttpUrl.parse(BASE_SFJ_URL)
            }
            //重建新的HttpUrl，修改需要修改的url部分
            val newFullUrl = oldHttpUrl!!.newBuilder()
                .scheme(newBaseUrl!!.scheme())
                .host(newBaseUrl.host())
                .port(newBaseUrl.port())
                .build()
            //因为正常baseurl仅仅到端口，这里根据自己的业务处理端口之后的路径，如果不需要替换，直接使用builder.url(newFullUrl).build()
//            val newUrl = newFullUrl.toString().replace("hantangframdev/", "")
            //重建这个request，通过builder.url(newUrl).build()
            //然后返回一个response至此结束修改
            return chain.proceed(newBuilder.url(newFullUrl).build())
        }
        return chain.proceed(request)


    }
}